package xyz.syyrjx.blog.util.ai;

import com.alibaba.dashscope.aigc.imagesynthesis.ImageSynthesis;
import com.alibaba.dashscope.aigc.imagesynthesis.ImageSynthesisParam;
import com.alibaba.dashscope.aigc.imagesynthesis.ImageSynthesisResult;
import com.alibaba.dashscope.exception.NoApiKeyException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import xyz.syyrjx.blog.entity.ai.AiDialogue;
import xyz.syyrjx.blog.exception.AiException;
import xyz.syyrjx.blog.util.CachePool;
import xyz.syyrjx.blog.util.ConstValuePool;
import xyz.syyrjx.blog.util.RandomUtil;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author 大地崩坏苍蝇兽
 * @date 2024/2/28 18:03
 * @description 通义万象服务类
 * @since v0.0.1
 */
@Component
public class WanxModelService implements AiModelService{

    private static final Logger logger = LoggerFactory.getLogger(WanxModelService.class);

    @Override
    public String answer(String prompt, HttpServletRequest request, String identity) throws InterruptedException {
        ImageSynthesis is = new ImageSynthesis();
        ImageSynthesisParam param =
                ImageSynthesisParam.builder()
                        .negativePrompt(ConstValuePool.IMAGE_NEGATIVE_PROMPT)
                        .model(ImageSynthesis.Models.WANX_V1)
                        .seed(RandomUtil.randomPositiveInteger())
                        .n(1)
                        .size("1024*1024")
                        .prompt(prompt)
                        .build();

        ImageSynthesisResult result = null;
        try {
            result = is.call(param);
        } catch (NoApiKeyException e) {
            throw new AiException("调用通义万象缺少ApiKey",e);
        }
        List<Map<String, String>> results = result.getOutput().getResults();
        if (results == null || results.size() == 0) {
            throw new AiException("调用通义万象返回结果为空:" +
                    result.getOutput().getCode() +
                    result.getOutput().getMessage());
        }
        List<AiDialogue> aiDialogues = CachePool.AI_DIALOGUE_LIST_MAP.get(identity)
                .computeIfAbsent(ConstValuePool.WANX_DIALOGUES, k -> new ArrayList<>());
        aiDialogues.add(AiDialogue.createUserDialogue(prompt));
        String resUrl = results.get(0).get("url");
        AiLogUtil.logDialogues(logger,
                "通义万象",
                prompt,
                resUrl,
                request);
        aiDialogues.add(AiDialogue.createAssistantDialogue("<img width='512px' height='512px' src='" + resUrl + "'/>"));
        return resUrl;
    }
}
